<template>
  <view class="word-detail-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <button class="btn-back" @click="goBack">
        <uni-icon type="left" size="18" color="#333"></uni-icon>
      </button>
      <text class="title">单词详情</text>
      <button class="btn-more" @click="showMoreOptions">
        <uni-icon type="more" size="18" color="#333"></uni-icon>
      </button>
    </view>

    <!-- 单词信息卡片 -->
    <view class="word-info-card">
      <view class="word-pronunciation">
        <text class="word-text">{{ word.content }}</text>
        <button class="btn-play" @click="playPronunciation">
          <uni-icon type="volume-medium" size="24" color="#1989fa"></uni-icon>
        </button>
      </view>
      <text class="phonetic" v-if="word.phonetic">英 {{ word.phonetic }}</text>
      
      <view class="word-meanings">
        <view class="meaning-item" v-for="(meaning, index) in word.meanings" :key="index">
          <text class="part-of-speech">{{ meaning.partOfSpeech }}</text>
          <text class="definition">{{ meaning.definition }}</text>
          
          <view class="examples" v-if="meaning.examples && meaning.examples.length > 0">
            <text class="example-label">例句:</text>
            <text class="example-text" v-for="(example, exIndex) in meaning.examples" :key="exIndex">
              • {{ example }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 相关信息卡片 -->
    <view class="related-info-card">
      <view class="info-item">
        <text class="info-label">学习进度</text>
        <view class="progress-info">
          <text class="progress-text">{{ word.progress }}/5</text>
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: `${word.progress * 20}%` }"></view>
          </view>
        </view>
      </view>
      
      <view class="info-item">
        <text class="info-label">学习次数</text>
        <text class="info-value">{{ word.studyCount }}次</text>
      </view>
      
      <view class="info-item">
        <text class="info-label">最近学习</text>
        <text class="info-value">{{ formatDate(word.lastStudyTime) }}</text>
      </view>
      
      <view class="info-item">
        <text class="info-label">所属单词集</text>
        <text class="info-value">{{ word.wordSet || '未分类' }}</text>
      </view>
    </view>

    <!-- 学习操作按钮 -->
    <view class="learning-actions">
      <button class="btn-primary" @click="startLearning">开始学习</button>
      <button class="btn-secondary" @click="addToPlan">添加到学习计划</button>
    </view>

    <!-- 相关词汇 -->
    <view class="related-words" v-if="relatedWords.length > 0">
      <text class="section-title">相关词汇</text>
      <view class="related-words-list">
        <button 
          class="related-word-item" 
          v-for="relatedWord in relatedWords" 
          :key="relatedWord.id"
          @click="goToRelatedWordDetail(relatedWord.id)"
        >
          <text class="related-word-text">{{ relatedWord.content }}</text>
          <text class="related-word-translation">{{ relatedWord.translation }}</text>
        </button>
      </view>
    </view>

    <!-- 操作菜单 -->
    <uni-popup ref="actionPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">操作选项</text>
          <button class="close-popup-btn" @click="closeActionPopup">
            <uni-icon type="close" size="20" color="#999"></uni-icon>
          </button>
        </view>
        <view class="popup-actions">
          <button class="popup-action-item" @click="editWord">
            <uni-icon type="compose" size="20" color="#1989fa"></uni-icon>
            <text>编辑单词</text>
          </button>
          <button 
            class="popup-action-item"
            @click="toggleFavorite"
          >
            <uni-icon 
              :type="word.isFavorite ? 'star-filled' : 'star'" 
              size="20" 
              color="#ffb400"
            ></uni-icon>
            <text>{{ word.isFavorite ? '取消收藏' : '收藏单词' }}</text>
          </button>
          <button class="popup-action-item" @click="shareWord">
            <uni-icon type="share" size="20" color="#07c160"></uni-icon>
            <text>分享单词</text>
          </button>
          <button class="popup-action-item danger" @click="deleteWord">
            <uni-icon type="trash" size="20" color="#e64340"></uni-icon>
            <text>删除单词</text>
          </button>
        </view>
        <button class="cancel-btn" @click="closeActionPopup">取消</button>
      </view>
    </uni-popup>

    <!-- 发音加载中提示 -->
    <uni-loading-mask 
      :visible="isPlayingAudio" 
      message="发音播放中..."
    ></uni-loading-mask>
  </view>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { wordAPI } from '../../services/apiService'

export default {
  name: 'WordDetail',
  components: {
    uniPopup: uni.Popup,
    uniLoadingMask: uni.LoadingMask
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const wordId = route.query.id || ''
    
    // 状态管理
    const word = ref({
      id: '',
      content: '',
      phonetic: '',
      meanings: [],
      progress: 0,
      studyCount: 0,
      lastStudyTime: '',
      wordSet: '',
      isFavorite: false
    })
    
    const relatedWords = ref([])
    const isLoading = ref(false)
    const isPlayingAudio = ref(false)
    const actionPopup = ref(null)
    
    // 加载单词详情
    const loadWordDetail = async () => {
      if (!wordId) {
        uni.showToast({ title: '单词ID无效', icon: 'none' })
        return
      }
      
      isLoading.value = true
      try {
        // 实际项目中应从API获取数据
        // const response = await wordAPI.getWordDetail(wordId)
        // word.value = response.data
        
        // 模拟数据
        word.value = generateMockWordDetail(wordId)
        
        // 加载相关词汇
        loadRelatedWords()
      } catch (error) {
        console.error('加载单词详情失败:', error)
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        isLoading.value = false
      }
    }
    
    // 生成模拟单词详情数据
    const generateMockWordDetail = (id) => {
      const mockWords = {
        '1': {
          id: 1,
          content: 'hello',
          phonetic: '/həˈloʊ/',
          meanings: [
            {
              partOfSpeech: 'int.',
              definition: '你好',
              examples: [
                'Hello, how are you?',
                'Hello, nice to meet you.'
              ]
            },
            {
              partOfSpeech: 'n.',
              definition: '问候，招呼',
              examples: [
                'He gave me a friendly hello.'
              ]
            }
          ],
          progress: 3,
          studyCount: 12,
          lastStudyTime: '2023-06-01T10:00:00Z',
          wordSet: '基础词汇',
          isFavorite: true
        },
        '2': {
          id: 2,
          content: 'world',
          phonetic: '/wɜːrld/',
          meanings: [
            {
              partOfSpeech: 'n.',
              definition: '世界',
              examples: [
                'The world is a beautiful place.',
                'Hello world!'
              ]
            },
            {
              partOfSpeech: 'n.',
              definition: '地球',
              examples: [
                'Saving the world is our responsibility.'
              ]
            }
          ],
          progress: 2,
          studyCount: 8,
          lastStudyTime: '2023-06-01T10:05:00Z',
          wordSet: '基础词汇',
          isFavorite: false
        }
      }
      
      // 如果找不到对应ID的单词，返回默认单词
      return mockWords[id] || mockWords['1']
    }
    
    // 加载相关词汇
    const loadRelatedWords = async () => {
      try {
        // 实际项目中应从API获取数据
        // const response = await wordAPI.getRelatedWords(word.value.id)
        // relatedWords.value = response.data
        
        // 模拟数据
        relatedWords.value = [
          {
            id: 11,
            content: 'hello',
            translation: '你好'
          },
          {
            id: 12,
            content: 'greeting',
            translation: '问候'
          },
          {
            id: 13,
            content: 'hi',
            translation: '嗨'
          }
        ]
      } catch (error) {
        console.error('加载相关词汇失败:', error)
      }
    }
    
    // 播放单词发音
    const playPronunciation = async () => {
      isPlayingAudio.value = true
      try {
        // 实际项目中应调用API获取音频
        console.log('播放单词发音:', word.value.content)
        
        // 模拟播放音频
        const audio = uni.createInnerAudioContext()
        audio.src = `http://localhost:8080/api/tts/word/${word.value.content}?userId=1`
        audio.play()
        
        audio.onError((res) => {
          console.error('音频播放失败:', res.errMsg)
          uni.showToast({ title: '发音播放失败', icon: 'none' })
          isPlayingAudio.value = false
        })
        
        audio.onEnded(() => {
          isPlayingAudio.value = false
        })
      } catch (error) {
        console.error('播放发音失败:', error)
        uni.showToast({ title: '发音播放失败', icon: 'none' })
        isPlayingAudio.value = false
      }
    }
    
    // 显示更多选项
    const showMoreOptions = () => {
      actionPopup.value.open()
    }
    
    // 关闭操作菜单
    const closeActionPopup = () => {
      actionPopup.value.close()
    }
    
    // 编辑单词
    const editWord = () => {
      closeActionPopup()
      router.push(`/words/edit/${word.value.id}`)
    }
    
    // 切换收藏状态
    const toggleFavorite = () => {
      closeActionPopup()
      
      // 实际项目中应调用API更新收藏状态
      word.value.isFavorite = !word.value.isFavorite
      
      uni.showToast({
        title: word.value.isFavorite ? '收藏成功' : '取消收藏',
        icon: 'success'
      })
    }
    
    // 分享单词
    const shareWord = () => {
      closeActionPopup()
      
      // 实际项目中应调用分享API
      uni.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }
    
    // 删除单词
    const deleteWord = () => {
      closeActionPopup()
      
      uni.showModal({
        title: '确认删除',
        content: `确定要删除单词 "${word.value.content}" 吗？`,
        success: (res) => {
          if (res.confirm) {
            // 实际项目中应调用API删除单词
            console.log('删除单词:', word.value.id)
            uni.showToast({ title: '删除成功', icon: 'success' })
            
            // 删除成功后返回上一页
            setTimeout(() => {
              goBack()
            }, 1500)
          }
        }
      })
    }
    
    // 开始学习
    const startLearning = () => {
      router.push({ path: '/word-learning', query: { wordId: word.value.id } })
    }
    
    // 添加到学习计划
    const addToPlan = () => {
      // 实际项目中应调用API添加到学习计划
      uni.showToast({ title: '已添加到学习计划', icon: 'success' })
    }
    
    // 跳转到相关单词详情
    const goToRelatedWordDetail = (relatedWordId) => {
      // 可以选择刷新当前页面或打开新页面
      // 这里选择刷新当前页面
      router.push({ path: '/words/detail', query: { id: relatedWordId } })
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '从未学习'
      
      const date = new Date(dateString)
      const now = new Date()
      const diffTime = Math.abs(now - date)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 1) {
        return '昨天'
      } else if (diffDays < 7) {
        return `${diffDays}天前`
      } else if (diffDays < 30) {
        return `${Math.floor(diffDays / 7)}周前`
      } else if (diffDays < 365) {
        return `${Math.floor(diffDays / 30)}个月前`
      } else {
        return `${Math.floor(diffDays / 365)}年前`
      }
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadWordDetail()
    })
    
    return {
      word,
      relatedWords,
      isLoading,
      isPlayingAudio,
      actionPopup,
      playPronunciation,
      showMoreOptions,
      closeActionPopup,
      editWord,
      toggleFavorite,
      shareWord,
      deleteWord,
      startLearning,
      addToPlan,
      goToRelatedWordDetail,
      goBack,
      formatDate
    }
  }
}
</script>

<style scoped>
.word-detail-container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.btn-back, .btn-more {
  background: none;
  border: none;
  padding: 8px;
}

.word-info-card {
  background-color: #fff;
  padding: 24px;
  margin-bottom: 16px;
}

.word-pronunciation {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.word-text {
  font-size: 32px;
  font-weight: bold;
  color: #333;
}

.btn-play {
  background-color: #e0f7fa;
  border: none;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.phonetic {
  font-size: 16px;
  color: #999;
  font-style: italic;
  margin-bottom: 20px;
  display: block;
}

.word-meanings {
  margin-top: 8px;
}

.meaning-item {
  margin-bottom: 20px;
}

.part-of-speech {
  font-size: 14px;
  color: #1989fa;
  background-color: #e0f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  margin-right: 8px;
}

.definition {
  font-size: 16px;
  color: #333;
  line-height: 1.6;
}

.examples {
  margin-top: 12px;
  padding-left: 16px;
}

.example-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.example-text {
  font-size: 14px;
  color: #999;
  line-height: 1.8;
  display: block;
}

.related-info-card {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #666;
}

.info-value {
  font-size: 14px;
  color: #333;
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.progress-text {
  font-size: 14px;
  color: #333;
}

.progress-bar {
  width: 100px;
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #07c160;
  transition: width 0.3s ease;
}

.learning-actions {
  padding: 0 20px 20px;
  display: flex;
  gap: 12px;
}

.btn-primary {
  flex: 1;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
}

.btn-secondary {
  flex: 1;
  background-color: #f5f5f5;
  color: #333;
  border: none;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
}

.related-words {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  display: block;
}

.related-words-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.related-word-item {
  width: 100%;
  background-color: #f5f5f5;
  border: none;
  border-radius: 8px;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.related-word-text {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.related-word-translation {
  font-size: 14px;
  color: #666;
}

/* 弹窗样式 */
.popup-content {
  background-color: #fff;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  padding: 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.popup-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.close-popup-btn {
  background: none;
  border: none;
  padding: 4px;
}

.popup-actions {
  padding: 8px 0;
}

.popup-action-item {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  background: none;
  border: none;
  font-size: 16px;
  color: #333;
}

.popup-action-item.danger {
  color: #e64340;
}

.cancel-btn {
  width: 90%;
  margin: 16px auto;
  padding: 12px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .word-pronunciation {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .learning-actions {
    flex-direction: column;
  }
}
</style>